#%%
# https://github.com/michaelliao/learn-python/blob/master/email/fetchmail_pop3.py

import poplib
import MailConfig

#%%
class Pop3Mail():
    def __init__(self, mail_config: MailConfig.MailConfig):
        self.__mail_config = mail_config

    def connect(self):
        # 1. 连接服务器
        if self.__mail_config.ssl_pop3_port is not None:
            self.__server = poplib.POP3_SSL(self.__mail_config.pop_server, self.__mail_config.ssl_pop3_port)
        elif self.__mail_config.unssl_pop3_port is not None:
            self.__server = poplib.POP3(self.__mail_config.pop_server, self.__mail_config.unssl_pop3_port)
        else:
            self.__server = poplib.POP3(self.__mail_config.pop_server)


        # 可选:打印POP3服务器的欢迎文字:
        print(self.__server.getwelcome())

        # 2.授权
        self.__server.user(self.__mail_config.user)
        self.__server.pass_(self.__mail_config.passwd)

        # 3.查询邮件数量和占用空间
        print('邮件数量: %s. 邮件总大小: %s' % self.__server.stat())

    def fetch(self)->list:
        '''
        '''
        # 4.返回所有邮件的编号
        resp, mails, octets = self.__server.list()
        print(mails)# 可以查看返回的列表类似['1 82923', '2 2184', ...]


        # 5. 获取一封邮件, 注意索引号从1开始:
        ret = []
        for i in range(1, len(mails) + 1):
            resp, lines, octets = self.__server.retr(i) # 索引号越大，表明邮件越新

            # lines存储了邮件的原始文本的每一行,
            # 可以获得整个邮件的原始文本:
            msg_content = b'\r\n'.join(lines)

            ret.append(msg_content)
        return ret
    
    def delete(self, inx):
        '''
        inx：要删除的邮件在邮件列表中的索引
        '''
        self.__server.dele(inx)

    def quit(self):
        self.__server.quit()


